/**
 * @param {*} options 
 */
var DataHandler = function(options){
    var t = this;
    t.options = $.parseJSON(JSON.stringify(options));
    t.$dom = $(options.container);
    t.$dom.html(DataHandler.showChartTpl.render({height:t.$dom.width() }));
    
    t._init_event_();
    t._load_({
    	"userConditions":t.options.userConditions
    });
}
/**
 * 重新加载
 */
DataHandler.prototype.reload = function(userConditions){
	var t = this;
	t.options.userConditions = userConditions
	t._load_({
		"userConditions":t.options.userConditions
    });
}
/**
 * 加载并渲染数据
 */
DataHandler.prototype._load_=function(params){
	var t = this;
	var options = t.options;
	params.designId = options.designId;
	cmp.dialog.loading();
	rptApi.getStatsPieResult({},params,{
		success:function(rs){
			cmp.dialog.loading(false);
			var isEmpty = (undefined == rs || undefined ==  rs.data) || function isEmptyObject(data){   
				for (var key in data){
					return false;
				}　　
				return true;
			}(rs.data);
			if(isEmpty){
				t.$dom.html("<div class='no-data-text'>"+cmp.i18n("report.common.nodata")+"</div>");
				DataHandler.alert(cmp.i18n("report.common.nodata"));
				return;
			}
			if(!rs.success){
				DataHandler.alert(rs.msg);
				return;
			}
			
			t.$dom.html(DataHandler.showChartTpl.render({height:t.$dom.width() }));
			var data = rs.data;
			
			var rowHeaders = [], statsFields = [], colHeader , fields = rs.fields , colData = rs.colData ;
			for(var i = 0, len1 = fields.length; i < len1; i++){
				var field = fields[i];
				if('H' == field.type){
					rowHeaders.push(field);
				}else if('S' == field.type){
					statsFields.push(field);
				}else if('C' == field.type){
					colHeader = field;
				}
			}
			t._data_ = data ,t._colData_ = colData, t._rowHeaders_ = rowHeaders ,t._statsFields_ = statsFields , t._colHeader_ = colHeader;
			
			//交叉项在前 统计项在后
			var opHtml = '';
			if(undefined != colHeader){
				opHtml += DataHandler.opCrossTpl.render({colData:colData});
	        }
			opHtml += DataHandler.opStatsTpl.render({statsFields:statsFields});
			t.$dom.find(".st-ct .op-ct").html(opHtml);
			t.showContentItem();
			
			
		},
		error:function(error){
			cmp.dialog.loading(false);
			var cmpHandled = cmp.errorHandler(error);
			if (!cmpHandled) {
				if (error.message) {
					DataHandler.alert(error.message);
				} else {
					DataHandler.alert(cmp.toJSON(error));
				}
			}
		}
	});
}
/**
 * 显示内容
 */
DataHandler.prototype.showContentItem = function(){
	var t = this;
	var rowHeaders = t._rowHeaders_ , statsFields = t._statsFields_, colHeader = t._colHeader_ , data = t._data_, colData = t._colData_ ;
	
	var fieldKey = t.$dom.find(".st-ct .op-ct .stats-st").val() ;
	var showField = DataHandler.getStatsField(statsFields , fieldKey);
	var key = showField.cellKey;
	if(undefined != colHeader){
		var crossIndex = t.$dom.find(".st-ct .op-ct .cross-st").val() || 0;
		key = crossIndex+'_'+key;
	}
    var pieData = data[key] || [];
    
    var serieData = [] ,total = 0;
    for(var j = 0, len2 = pieData.length; j < len2; j++){
    	var rowData = pieData[j];
    	var name ,penetratable = showField.penetratable;
    	
    	if(null != rowData['other']){
			name = rowData['other'].d;
			penetratable = false;
		}else{
			for(var k = 0, len3 = rowHeaders.length; k < len3; k++){
				var field = rowHeaders[k] , cellData = rowData[field.cellKey];
				var display = (cellData.d == null ) ? "" : cellData.d;
				name = (k == 0) ? display : (name + '/' + display);
			}
		}
		var cellData = rowData[showField.cellKey];
    	var value = (null == cellData.v) ? 0 : Math.floor(cellData.v);
        serieData[j] = {value:value, name:name,penetratable:penetratable};
        total += value;
    }
    
    var centerDisplay = showField.display;
    if(centerDisplay.length > 6){
    	centerDisplay = centerDisplay.substring(0,6) + '...';
    }
    var labelTotal = total;
    if(labelTotal > 1000000000000){
    	labelTotal = total/1000000000000;
    	labelTotal = labelTotal.toFixed(1) + '兆';
    }else if(labelTotal > 100000000){
    	labelTotal = total/100000000;
    	labelTotal = labelTotal.toFixed(1) + '亿';
    }else if(labelTotal > 10000){
    	labelTotal = total/10000;
    	labelTotal = labelTotal.toFixed(1) + cmp.i18n("report.result.common.w");
    }
    centerDisplay = centerDisplay + "\n"+labelTotal;
    
    var defaultColors = DataHandler.defaultColors;
    //显示表格
    var listTitle = showField.display + ":" + labelTotal;
    var listHtml = DataHandler.listCtTpl.render({title:listTitle,serieData:serieData,defaultColors:defaultColors,total:total});
    t.$dom.find(".list-ct").html(listHtml);
    //显示图
    var option = {
    		color: defaultColors,
            series : [{
                type:'pie',
                selectedMode : false,
                avoidLabelOverlap: false,
        		hoverAnimation: false,
                radius : [0, '40%'],
                itemStyle:{
                	normal:{
                		color : '#fff'
                	}
                },
                label: {
                    normal: {
                        show : true,
                        fontSize:14,
        				position : 'center',
        				formatter :'{b}',
        				textStyle : {
        					color : '#666',
        					fontSize : 12
        				}
                    },
                    emphasis : {
                        show : true,
                        fontSize:14,
        				position : 'center',
        				formatter :'{b}',
        				textStyle : {
        					color : '#666',
        					fontSize : 12
        				}
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data:[{value:1,name:centerDisplay}]
            },{
                type:'pie',
//                name:statsKey,
        		minAngle: 5,
        		selectedMode: 'single',
        		radius: ['41%', '80%'],
        		avoidLabelOverlap: false,
        		hoverAnimation: false,
        		label: {
        			normal: {
        				show: true,
        				position: 'inside',
        				formatter: function(params, ticket, callback){
                            var percent = params.percent;
                            if(Math.floor(percent) < 5){
                                return "";
                            }
                            return percent + "%";
                        }
        			}
        		},
        		itemStyle: {
        			normal: {
        				borderColor: '#ffffff',
        				borderWidth: 5,
        				borderType: 'solid'
        			}
        		},
        		labelLine: {
        			normal: {
        				show: false
        			}
        		},
                data:serieData
            }]
        };
    var et = echarts.init(t.$dom.find(".chart-ct")[0]);
    et.showLoading({
        text: 'loading...'
    });
    et.hideLoading();
    et.setOption(option,true);
    //图事件
    et.on('click', function (params) {
    	var listData = serieData;
    	if(params.seriesIndex == 0){//中间区域
    		var dataIndex = t.$dom.find(".list-ct .list-table tr").attr("dataIndex");
    		et.dispatchAction({
    			type: 'pieUnSelect',
			    seriesIndex: 1,
			    dataIndex: dataIndex
    		});
    	}else{
    		var rowData = params.data;
    		rowData.dataIndex = params.dataIndex;
    		listData = [rowData];
    	}
    	var listHtml = DataHandler.listCtTpl.render({title:listTitle,serieData:listData,defaultColors:defaultColors,total:total});
    	t.$dom.find(".list-ct").html(listHtml);
    });
    
}
/**
 * 初始化事件
 */
DataHandler.prototype._init_event_ = function(){
	var t = this;
	t.$dom.on("change",".st-ct .op-ct .cross-st,.st-ct .op-ct .stats-st",function(){
		t.showContentItem();
	}).on("click",".st-ct .list-ct .list-table .penet",function(){
		if(t.options.isPreview){
			return;
		}
		var rowHeaders = t._rowHeaders_ , statsFields = t._statsFields_, colHeader = t._colHeader_ , data = t._data_, colData = t._colData_ ;
		var fieldKey = t.$dom.find(".st-ct .op-ct .stats-st").val();
		var showField =  DataHandler.getStatsField(statsFields , fieldKey);
		
		var key = showField.cellKey;
		if(undefined != colHeader){
			var crossIndex = t.$dom.find(".st-ct .op-ct .cross-st").val() || 0;
			key = crossIndex+'_'+key;
		}
	    var pieData = data[key] || [];
	    var dataIndex = $(this).attr("dataIndex");
	    var rowData = pieData[dataIndex];
	    
		if(!showField.penetratable || null != rowData['other']){
			return;
		}
		var titleName = '' , values = {} ;
		for(var k = 0, len3 = rowHeaders.length; k < len3; k++){
			var hField = rowHeaders[k];
			var cellData = rowData[hField.cellKey];
			var display = (cellData.d == null ) ? "" : cellData.d;
			titleName = titleName + display + '_';
			values[hField.fieldKey]= cellData.v;
		}
		if(null != colHeader){//有交叉项
			var cellData = colData[crossIndex];
			var display = (cellData.d == null ) ? "" : cellData.d;
			titleName = titleName + display + '_';
			values[colHeader.fieldKey]= cellData.v;
		}
		
		titleName += showField.display;
		titleName += '(';
		if (showField.calcType == 'count') {
			titleName += cmp.i18n("report.result.common.count");//cmp.i18n("report.common.nodata")
		} else if (showField.calcType == 'sum') {
			titleName += cmp.i18n("report.result.common.sum");
		} else if (showField.calcType == 'avg') {
			titleName += cmp.i18n("report.result.common.avg");
		} else if (showField.calcType == 'max') {
			titleName += cmp.i18n("report.result.common.max");
		} else if (showField.calcType == 'min') {
			titleName += cmp.i18n("report.result.common.min");
		} else if (showField.calcType == 'earliest') {
			titleName += cmp.i18n("report.result.common.earliest");
		} else if (showField.calcType == 'latest') {
			titleName += cmp.i18n("report.result.common.latest");
		}
		titleName += ')';
		var titleValue = rowData[showField.cellKey].v;
		titleValue = (null == titleValue) ? 0 : titleValue;
		
		rptApi.getStatsPenetrateInfo({},{designId:t.options.designId},{
			success:function(rs){
				if(rs.penetrateMode == 'query'){
					RptUtils.load_jscss([vreportPath + "/vreport_m_api.s3js"],[],function(){
						var toDesignId = rs.designId ,headFieldMaps = rs.headFieldMaps , filterFieldMaps = rs.filterFieldMaps;
						var filterValue = RptUtils.getFilterValue(values,t.options.userConditions,headFieldMaps,filterFieldMaps);
						vreportApi.reportView({rptInfo:{module:'4',relatedId:toDesignId,filterValue:filterValue}});
					});
				}else{
					var params = {titleName:titleName,titleValue:titleValue,
							designId:t.options.designId,
							statsField:showField.fieldKey,
							userConditions:t.options.userConditions,
							fieldValues:values
					};
					cmp.href.next(vreportPath + "/html/defaultPenetList.html",params);
				}
				cmp.dialog.loading(false);
			},
			error:function(error){
				cmp.dialog.loading(false);
				var cmpHandled = cmp.errorHandler(error);
				if (!cmpHandled) {
					if (error.message) {
						DataHandler.alert(error.message);
					} else {
						DataHandler.alert(cmp.toJSON(error));
					}
				}
			}
		});
	});
}

/**
 * 查找统计项
 */
DataHandler.getStatsField = function(statsFields , fieldKey){
	if(undefined == fieldKey){
		return statsFields[0];
	}
	for(var i = 0, len1 = statsFields.length; i < len1; i++){
		if(fieldKey == statsFields[i].fieldKey){
			return statsFields[i];
		}
	}
	return ;
}
DataHandler.alert = function(tips){
	cmp.notification.alert(tips);
}

DataHandler.showChartTpl = laytpl('\
	<div class="st-ct">\
		<div class="op-ct"></div>\
		<div>\
			<div class="chart-ct" style="height:{{d.height }}px"></div>\
		</div>\
		<div class="list-ct"></div>\
	</div>');

DataHandler.opCrossTpl = laytpl('\
	{{# if(d.colData.length == 1){ }}\
		<div class="op-ct-label"><lable>{{=d.colData[0].d }}</lable></div>\
	{{# }else{ }}\
		<select class="cross-st">\
			{{#\
				for(var i=0;i<d.colData.length;i++){\
			}}\
				<option value="{{i }}">{{=d.colData[i].d }}</option>\
			{{#\
				}\
			}}\
		</select>\
	{{# } }}');

DataHandler.opStatsTpl = laytpl('\
	{{# if(d.statsFields.length == 1){ }}\
		<div class="op-ct-label"><lable>{{=d.statsFields[0].display }}</lable></div>\
	{{# }else{ }}\
		<select class="stats-st">\
			{{#\
				for(var i=0;i<d.statsFields.length;i++){\
					var fieldKey = d.statsFields[i].fieldKey;\
			}}\
				<option value="{{=fieldKey }}">{{=d.statsFields[i].display }}</option>\
			{{#\
				}\
			}}\
		</select>\
	{{# } }}');
DataHandler.listCtTpl = laytpl('\
	{{# var  wd = window.innerWidth, nameWd = wd - 220; }}\
	<div class="title-row"><span>{{=d.title }}</span></div>\
	<div class="list-table">\
	    <table class="" border="0" cellspacing="0" cellpadding="0">\
	        <tbody>\
				{{# for(var i = 0, len1 = d.serieData.length; i < len1; i++){ \
					var dataIndex = (undefined == d.serieData[i].dataIndex ) ? i : d.serieData[i].dataIndex; \
					var size = dataIndex % d.defaultColors.length , p = (d.total == 0)? 0 : Math.round(d.serieData[i].value/d.total*10000)/100 ;\
					var penetratable = d.serieData[i].penetratable;\
				}}\
	            <tr dataIndex="{{dataIndex }}" class="{{# if(penetratable){ }}penet{{# } }}">\
	                <td class="row-n">\
	                    <div class="row-color">\
	                        <div style="background-color:{{d.defaultColors[size] }};"></div>\
	                    </div>\
	                    <div class="row-name" style="width:{{nameWd }}px">{{=d.serieData[i].name }}</div>\
	                </td>\
	                <td class="row-v">\
	                    <div class="row-percent">{{p}}%</div>\
	                </td>\
	                <td class="row-v">\
	                    <div class="row-value">{{Math.floor(d.serieData[i].value)}}</div>\
	                </td>\
					<td class="row-i">{{# if(penetratable){ }}<i class="cmp-icon cmp-icon-arrowright"></i>{{# } }}</td>\
	            </tr>\
				{{# } }}\
	        </tbody>\
	    </table>\
	</div>');

DataHandler.defaultColors = ["#67bfff", "#20cf6d", "#f3b700", "#ec4c35", "#9d56ba", "#6799ff", "#19c170", "#f3ce00", "#ec6035", "#a63eb9", "#3664e6", "#a0cf20", "#f3e500", "#ec8335", "#b928c2", "#173dce", "#7fcf20", "#ebf300", "#f39500", "#C22883"];


